import sys
import subprocess
from PyQt5 import QtWidgets
from iperf3 import *
from dataclasses import dataclass


@dataclass
class cmd_opt:
    ip: str = None
    port: int = 5201
    timeout: int = 30
    thread_num: int = 1
    bandwidth: str = "1G"
    proto: str = "tcp"


class Ui_DockWidget_Impl(Ui_DockWidget):
    def __init__(self, DockWidget):
        super().__init__()
        self.opt = cmd_opt()
        self.setupUi(DockWidget)
        self.callback_init()

    def callback_init(self):
        self.btn_start_stop.clicked.connect(self.btn_start_stop_callback)

    def btn_start_stop_callback(self):
        ip = self.input_ip.text()
        port = self.input_port.text()
        timeout = self.box_timeout.currentText()
        proto = self.box_proto.currentText()
        bandwidth = self.input_bandwidth.text()
        num = self.input_num.text()
        cmd_opt = ""
        if ip == "":
            self.output_result.append("请输入ip地址")
            return
        else:
            cmd_opt += f"-c {ip} "

        if port == "":
            pass
        else:
            cmd_opt += f"-p {port} "

        if timeout == "":
            pass
        else:
            cmd_opt += f"-t {timeout} "

        if proto == "tcp":
            pass
        else:
            cmd_opt += f"-u "
        
        if bandwidth == "":
            pass
        else:
            cmd_opt += f"-b {bandwidth} "
            
        if num == "":
            pass
        else:
            cmd_opt += f"-P {num} "

        cmd = f"iperf3 {cmd_opt}"
        print(cmd)
        self.shell_cmd_realtime_output(cmd)
    
    def shell_cmd_realtime_output(self, cmd):
        self.output_client_result.clear()
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True,)
        # 循环读取输出
        for line in iter(p.stdout.readline, ""):
            buf = line.strip()
            print(">",buf)
            self.output_client_result.append(buf)

        if p.returncode == 0:
            print("Subprogram success")
            # self.output_client_result.append("ok ..")
        else:
            print("Subprogram failed")
            # self.output_client_result.append("fail ..")

        p.stdout.close()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    DockWidget = QtWidgets.QDockWidget()
    ui = Ui_DockWidget_Impl(DockWidget)
    DockWidget.show()
    sys.exit(app.exec_())
